package com.msa.msaportal.webservice;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.apache.commons.codec.binary.Base64;

import net.sf.json.JSONObject;

import com.msa.msaportal.common.web.ConstantUntil;
import com.msa.msaportal.entity.Portalfooter;
import com.msa.msaportal.entity.PortalheaderEntity;
import com.msa.msaportal.entity.PortalCssEntity;
import com.msa.msaportal.entity.Template;
import com.msa.msaportal.service.IFooterService;
import com.msa.msaportal.service.IHeaderService;
import com.msa.msaportal.service.IPortalCssEntityService;
import com.msa.msaportal.service.ITemplateService;

public class TemplateOrStylInterfaceImpl implements TemplateOrStylInterface {
	@Resource(name = "templateManager")
	private ITemplateService templateManager;

	@Resource(name = "portalcssManager")
	private IPortalCssEntityService cssManager;

	@Resource(name = "footerService")
	private IFooterService footerService;

	@Resource(name = "headerService")
	private IHeaderService headerService;

	String success = "{'result':'0','info':'操作成功!'}";
	String fail = "{'result':'1','info':'失败原因!'}";
	String exception = "{'result':'2','info':'接口异常!'}";

	// 获得项目路径
	String fileSaveDataPathJsp = ResourceBundle.getBundle("commonurl").getString("fileSaveDataPathJsp");
	String fileSaveDataPathStyle = ResourceBundle.getBundle("commonurl").getString("fileSaveDataPathStyle");
	//String fileSaveDrivePath = getClass().getResource("/").getFile().toString().replace("WEB-INF/classes/", "");

	String fileSaveDrivePath = getClass().getResource("/").getFile().toString().replace("build/classes/", "")+"WebContent/";

	@Override
	public String addTemplateOrStyle(String jsonst) {

		// 解析json数据并做处理
		try {

			JSONObject fromObject = JSONObject.fromObject(jsonst);
			String fileType = fromObject.getString("fileType");
			String templateOrStyleName = fromObject.getString("templateOrStyleName");
			String orgName = fromObject.getString("orgName");
			String orgId = fromObject.getString("orgId");
			if (orgId.trim().equals("")) {
				return "{'result':'4','info':'orgId不能为空!'}";
			}
			String description = fromObject.getString("description");
			String p = fromObject.getString("public");
			String author = fromObject.getString("author");
			String authorId = fromObject.getString("authorId");
			String alter = fromObject.getString("alter");
			String alterId = fromObject.getString("alterId");
			String createTime = fromObject.getString("createTime");
			String updateTime = fromObject.getString("updateTime");
			String files = fromObject.getString("files");
			String fileName = fromObject.getString("fileName");
			String NameSuffix = fileName.substring(fileName.lastIndexOf("."),fileName.length());
			String templateOrStyleId = fromObject.getString("templateOrStyleId");

			// 模板保存
			if (fileType.equals("jsp")) {
				// 模板需要关联头和尾
				// String headerId = fromObject.getString("headerId");
				// String footerId = fromObject.getString("footerId");

				Template template = new Template();
				template.setCreatetime(createTime);
				template.setCreateuserid(authorId);
				template.setCreateusername(author);

				if (p.equals("1")) {
					template.setIspublic(true);
				} else {
					template.setIspublic(false);
				}
				template.setOrgid(orgId);
				template.setOrgname(orgName);
				template.setTemplate_name(templateOrStyleName);

				template.setTsource_id(templateOrStyleId);
				template.setUpdatetime(updateTime);
				template.setUpdateusername(alter);
				template.setUpdateuserid(alterId);

				// 保存文件
				byte[] fileByte = Base64.decodeBase64(files);
				// 查看父目录是否存在
				// String fatherpath=filePath1+"/file/jsp";
				//fileSaveDrivePath = getClass().getResource("/").getFile().toString();
				System.out.println("11111111111122222222222333333333333:"+fileSaveDrivePath + fileSaveDataPathJsp);
				File file = new File(fileSaveDrivePath + fileSaveDataPathJsp);
				if (!file.exists()) {
					file.mkdirs();
				}
				File backupJsp=new File(ConstantUntil.BACKUPJSP_URL);
				if(!backupJsp.exists()){
					backupJsp.mkdirs();
				}
				DateFormat MONTH_FORMAT = new SimpleDateFormat(
						"yyyyMMddHHmmss");
				int randomnum = (int) (Math.random()*9000+1000);
				String datetime = MONTH_FORMAT.format(new Date())+randomnum;
				String path = fileSaveDrivePath + fileSaveDataPathJsp + "/"
						+ datetime + NameSuffix;
				try {
					FileOutputStream fileOutputStream = new FileOutputStream(
							path);
					FileOutputStream backupFileOut=new FileOutputStream(ConstantUntil.BACKUPJSP_URL+datetime + NameSuffix);
					fileOutputStream.write(fileByte);
					backupFileOut.write(fileByte);
					fileOutputStream.flush();
					backupFileOut.flush();
					fileOutputStream.close();
					backupFileOut.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					String fail = "{'result':'1','info':'文件上传失败!'}";
					return fail;
				}
				String path1 = fileSaveDataPathJsp + "/" + datetime
						+ NameSuffix;
				template.setTemplate_path(path1);
				// 保存模板
				try {

					templateManager.save(template);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					String fail = "{'result':'1','info':'操作失败!'}";
					return fail;
				}
				// 样式保存
			}
			if (fileType.equals("js") || fileType.equals("css")) {
				PortalCssEntity css = new PortalCssEntity();

				css.setCreateuserName(author);
				css.setCreatetime(createTime);
				css.setCreateuserId(authorId);
				css.setCsourceId(templateOrStyleId);
				css.setCssName(templateOrStyleName);
				if (p.equals("1")) {
					css.setIspublic(true);
				} else {
					css.setIspublic(false);
				}
				css.setOrgid(orgId);
				css.setOrgname(orgName);
				css.setUpdatetime(updateTime);
				css.setUpdateUsername(alter);
				css.setUpdateUserid(alterId);

				// 保存文件
				byte[] fileByte = Base64.decodeBase64(files);

				// 查看父目录是否存在
				// String fatherpath=filePath1 +"/file/style";
				File file = new File(fileSaveDrivePath + fileSaveDataPathStyle);
				File backupcssfile = new File(ConstantUntil.BACKUPSTYLE_URL);
				if (!file.exists()) {
					file.mkdirs();
				}
				if (!backupcssfile.exists()) {
					backupcssfile.mkdirs();
				}
				DateFormat MONTH_FORMAT = new SimpleDateFormat(
						"yyyyMMddHHmmss");
				int randomnum = (int) (Math.random()*9000+1000);
				String datetime = MONTH_FORMAT.format(new Date())+randomnum;
				String path = fileSaveDrivePath + fileSaveDataPathStyle + "/"
						+ datetime + NameSuffix;
				try {
					FileOutputStream fileOutputStream = new FileOutputStream(
							path);
					FileOutputStream backupFileOut=new FileOutputStream(ConstantUntil.BACKUPSTYLE_URL+datetime + NameSuffix);
					fileOutputStream.write(fileByte);
					backupFileOut.write(fileByte);
					fileOutputStream.flush();
					backupFileOut.flush();
					fileOutputStream.close();
					backupFileOut.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					String fail = "{'result':'1','info':'文件上传失败!'}";
					return fail;
				}
				String path1 = fileSaveDataPathStyle + "/" + datetime
						+ NameSuffix;
				css.setCssPath(path1);
				// 保存样式
				try {

					cssManager.save(css);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					String fail = "{'result':'1','info':'操作失败!'}";
					return fail;
				}

			}
			;

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return exception;
		}
		System.out.println(success);
		return success;

	}

	@Override
	public String delTemplateOrStyle(String jsonstr) {
		// TODO Auto-generated method stub
		try {

			// 解析json
			JSONObject fromObject = JSONObject.fromObject(jsonstr);
			String templateOrStyleId = fromObject
					.getString("templateOrStyleId");
			String fileType = fromObject.getString("fileType");
			// 判断是否包含多个id
			boolean contains = templateOrStyleId.contains(",");
			// 刪除樣式或模板同时删除上传文件
			if (fileType.equals("jsp")) {
				if (contains) {
					String[] idArray = templateOrStyleId.split(",");
					for (int i = 0; i < idArray.length; i++) {
						delTem(idArray[i]);
					}
				} else {
					delTem(templateOrStyleId);
				}
			} else if (fileType.equals("js") || fileType.equals("css")) {
				if (contains) {
					String[] idArray = templateOrStyleId.split(",");
					for (int i = 0; i < idArray.length; i++) {
						try {
							delCss(idArray[i]);
						} catch (Exception e) {
							return "{'result':'3','info':'Id:" + idArray[i]+ "被占用!'}";
						}
					}
				} else {
					try {
						delCss(templateOrStyleId);
					} catch (Exception e) {
						System.out.println("{'result':'3','info':'Id:" + templateOrStyleId + "被占用!'}");
						return "{'result':'3','info':'Id:" + templateOrStyleId + "被占用!'}";
					}
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return exception;
		}
		System.out.println("{'result':'0','info':'操作成功!'}");
		return "{'result':'0','info':'操作成功!'}";
	}

	public void delTem(String temId) {
		Template template = templateManager.findByTresourse_Id(temId);
		String template_path = template.getTemplate_path();
		String template_path1 = fileSaveDrivePath + template_path;
		//备份文件地址
		String backupTemUrl=ConstantUntil.BACKUP_PATH+template_path;
		
		if (template.getHeader() != null) {
			String logoUrl = template.getHeader().getLogo_url();
			String logoUrl1 = fileSaveDrivePath + logoUrl;
			File Url = new File(logoUrl1);
			if (Url.isFile() && Url.exists()) {
				Url.delete();
			}
			File backuplogo=new File(ConstantUntil.BACKUP_PATH+logoUrl);
			if (backuplogo.isFile() && backuplogo.exists()) {
				backuplogo.delete();
			}
		}
		File templatepath = new File(template_path1);
		File backuptemplate = new File(backupTemUrl);
		if (templatepath.isFile() && templatepath.exists()) {
			templatepath.delete();
		}
		if (backuptemplate.isFile() && backuptemplate.exists()) {
			backuptemplate.delete();
		}
		templateManager.delete(temId);

	}

	public void delCss(String cssId) {
		PortalCssEntity portalCssEntity = cssManager.findByCresourse_Id(cssId);
		cssManager.delete(cssId);

		String cssPath = portalCssEntity.getCssPath();
		String cssPath1 = fileSaveDrivePath + cssPath;
		//备份文件地址
		String backupcssPath = ConstantUntil.BACKUP_PATH + cssPath;
		
		File file = new File(cssPath1);
		
		File backupCssfile = new File(backupcssPath);
		
		if (file.isFile() && file.exists()) {
			file.delete();
		}
		if (backupCssfile.isFile() && backupCssfile.exists()) {
			backupCssfile.delete();
		}
	}

	@Override
	public String editTemplateAndCss(String json) {
		System.out.println("editjson::"+json);
		JSONObject fromObject = JSONObject.fromObject(json);
		String fileType = fromObject.getString("fileType");
		String templateOrStyleName = fromObject.getString("templateOrStyleName");
		String orgName = fromObject.getString("orgName");
		String orgId = fromObject.getString("orgId");
		if (orgId.trim().equals("")) {
			return "{'result':'4','info':'orgId不能为空!'}";
		}
		String p = fromObject.getString("public");
		String author = fromObject.getString("author");
		String authorId = fromObject.getString("authorId");
		String alter = fromObject.getString("alter");
		String alterId = fromObject.getString("alterId");
		String createTime = fromObject.getString("createTime");
		String updateTime = fromObject.getString("updateTime");
		String files = fromObject.getString("files");
		String fileName = fromObject.getString("fileName");
		String NameSuffix = fileName.substring(fileName.lastIndexOf("."),fileName.length());
		String templateOrStyleId = fromObject.getString("templateOrStyleId");
		if ("jsp".equals(fileType)) {
			// 模板需要关联头和尾
			Template template = templateManager.findByTresourse_Id(templateOrStyleId);
			if(template==null){
				String fail = "{'result':'1','info':'操作失败!'}";
				return fail;
			}
			template.setCreatetime(createTime);
			template.setCreateuserid(authorId);
			template.setCreateusername(author);

			if (p.equals("1")) {
				template.setIspublic(true);
			} else {
				template.setIspublic(false);
			}
			template.setOrgid(orgId);
			template.setOrgname(orgName);
			template.setTemplate_name(templateOrStyleName);

			template.setTsource_id(templateOrStyleId);
			template.setUpdatetime(updateTime);
			template.setUpdateusername(alter);
			template.setUpdateuserid(alterId);
			
			//删除旧文件
			String template_path = template.getTemplate_path();
			String template_path1 = fileSaveDrivePath + template_path;
			//备份文件地址
			String backupTemUrl=ConstantUntil.BACKUP_PATH+template_path;
			
			File templatepath = new File(template_path1);
			
			File backupTemFile = new File(backupTemUrl);
			
			if (templatepath.isFile() && templatepath.exists()) {
				templatepath.delete();
			}
			if (backupTemFile.isFile() && backupTemFile.exists()) {
				backupTemFile.delete();
			}

			// 保存新文件
			byte[] fileByte = Base64.decodeBase64(files);
			// 查看父目录是否存在
			File file = new File(fileSaveDrivePath + fileSaveDataPathJsp);
			
			if (!file.exists()) {
				file.mkdirs();
			}

			File backupJsp=new File(ConstantUntil.BACKUPJSP_URL);
			if(!backupJsp.exists()){
				backupJsp.mkdirs();
			}
			
			DateFormat MONTH_FORMAT = new SimpleDateFormat(
					"yyyyMMddHHmmss");
			int randomnum = (int) (Math.random()*9000+1000);
			String datetime = MONTH_FORMAT.format(new Date())+randomnum;
			String path = fileSaveDrivePath + fileSaveDataPathJsp + "/"
					+ datetime + NameSuffix;
			try {
				FileOutputStream fileOutputStream = new FileOutputStream(
						path);
				FileOutputStream backupFileOut=new FileOutputStream(ConstantUntil.BACKUPJSP_URL+datetime + NameSuffix);
				fileOutputStream.write(fileByte);
				backupFileOut.write(fileByte);
				fileOutputStream.flush();
				backupFileOut.flush();
				fileOutputStream.close();
				backupFileOut.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				String fail = "{'result':'1','info':'文件上传失败!'}";
				return fail;
			}
			String path1 = fileSaveDataPathJsp + "/" + datetime
					+ NameSuffix;
			template.setTemplate_path(path1);
			// 保存模板
			try {

				templateManager.updateTemplate(template);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				String fail = "{'result':'1','info':'操作失败!'}";
				return fail;
			}
		}else if("js".equals(fileType)|| "css".equals(fileType)) {
			
			PortalCssEntity css = cssManager.findByCresourse_Id(templateOrStyleId);
			if(css==null){
				String fail = "{'result':'1','info':'操作失败!'}";
				return fail;
			}
			css.setCreateuserName(author);
			css.setCreatetime(createTime);
			css.setCreateuserId(authorId);
			css.setCsourceId(templateOrStyleId);
			css.setCssName(templateOrStyleName);
			if (p.equals("1")) {
				css.setIspublic(true);
			} else {
				css.setIspublic(false);
			}
			css.setOrgid(orgId);
			css.setOrgname(orgName);
			css.setUpdatetime(updateTime);
			css.setUpdateUsername(alter);
			css.setUpdateUserid(alterId);
			
			//删除旧文件
			String cssPath = css.getCssPath();
			String cssPath1 = fileSaveDrivePath + cssPath;
			File oldfile = new File(cssPath1);
			if (oldfile.isFile() && oldfile.exists()) {
				oldfile.delete();
			}
			//备份文件删除
			File oldBackupFile=new File(ConstantUntil.BACKUP_PATH+cssPath);
			if (oldBackupFile.isFile() && oldBackupFile.exists()) {
				oldBackupFile.delete();
			}
			// 保存新文件
			byte[] fileByte = Base64.decodeBase64(files);

			// 查看父目录是否存在
			File file = new File(fileSaveDrivePath + fileSaveDataPathStyle);
			if (!file.exists()) {
				file.mkdirs();
			}
			File Backupcssfile = new File(ConstantUntil.BACKUPSTYLE_URL);
			if (!Backupcssfile.exists()) {
				Backupcssfile.mkdirs();
			}
			DateFormat MONTH_FORMAT = new SimpleDateFormat(
					"yyyyMMddHHmmss");
			int randomnum = (int) (Math.random()*9000+1000);
			String datetime = MONTH_FORMAT.format(new Date())+randomnum;
			String path = fileSaveDrivePath + fileSaveDataPathStyle + "/"
					+ datetime + NameSuffix;
			try {
				FileOutputStream fileOutputStream = new FileOutputStream(
						path);
				FileOutputStream Backupfileout=new FileOutputStream(ConstantUntil.BACKUPSTYLE_URL+datetime + NameSuffix);
				fileOutputStream.write(fileByte);
				Backupfileout.write(fileByte);
				fileOutputStream.flush();
				Backupfileout.flush();
				fileOutputStream.close();
				Backupfileout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				String fail = "{'result':'1','info':'文件上传失败!'}";
				return fail;
			}
			String path1 = fileSaveDataPathStyle + "/" + datetime
					+ NameSuffix;
			css.setCssPath(path1);
			// 保存样式
			try {

				cssManager.updateEntity(css);
			} catch (Exception e) {
				e.printStackTrace();
				String fail = "{'result':'1','info':'操作失败!'}";
				return fail;
			}

		}
		
		
		return success;
	}
}
